<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
//引用对应的命名空间
use Gregwar\Captcha\CaptchaBuilder;
use Session;

class LoginController extends Controller
{   
    //登录界面
    public function login(){
        return view('/admin/login');
    }

    //验证登录的方法
    public function checkLogin(Request $request){
        //验证 验证码是否正确
        $userInput = \Request::get('captcha');

        if (Session::get('milkcaptcha') != $userInput) {
            //用户输入验证码错误
            return error('/admin/login','输入验证码错误',2);
        } 

        //接收表单信息
        $uname = $request->input('uname');
        //dd($request);
        $upwd = md5($request->input('upwd'));

        //查询用户信息
        $result = DB::table('users')
                        ->where('uname','=',$uname)
                        ->where('upwd','=',$upwd)
                        ->select('uid','uname','uemail')
                        ->first();
        //验证用户是否存在和密码是否正确
        //var_dump($result);
        if($result){
            //查询到用户  写入session信息并跳转到后台首页
            $request->session()->put('isAdmin',true);//登录标志
            $request->session()->put('uid',$result['uid']);//用户ID
            $request->session()->put('uname',$result['uname']);//用户名
            $request->session()->put('uemail',$result['uemail']);//用户邮箱

            //跳转到后台首页
            return redirect('/admin/index');
        }else{
            //没查询到用户  回登陆页面
            return redirect('/admin/login');
        }

    }

    //退出登录方法
    public function logout(Request $request){
        //清除session信息
        $request->session()->flush();
        //跳转页面
        return redirect('admin/login');
    }   

    //生成验证码的方法
    public function vcode(){
        //生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();

        //把内容存入session
        Session::flash('milkcaptcha', $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();

    }
}
